<script setup lang="ts">
import { useRequest } from 'vue-request'
import { fetchProjectListAPI } from '@/apis/fetchProjectList'
import { useProjectConfigStore } from '@/store/projectConfig'
import { useUserInfoStore } from '@/store/userInfo'

const router = useRouter()
const userInfoStore = useUserInfoStore()
const projectConfigStore = useProjectConfigStore()

/* ------------------------------- Tabs START ------------------------------- */
const tabConfiguration = ref([{ name: '全部' }, { name: '施工中' }, { name: '售后中' }])
const selectedTabName = ref<'全部' | '施工中' | '售后中'>('全部')
/* -------------------------------- Tabs END -------------------------------- */

/* ------------------------------- 列表数据 START ------------------------------- */
// 搜索
const { searchText, isOpenSearch, searching, searchResult, fetchSearchResult } = useSearch<Project>(search)

const { data: dataList, loading, refreshAsync } = useRequest<Project[]>(() => fetchProjectListAPI({
  status: projectConfigStore.projectStatusCode[selectedTabName.value],
  keyword: searchText.value.length > 0 ? searchText.value : undefined,
}, userInfoStore.userInfo!.token!).then(res => res.data!.data))

const finalList = computed(() => {
  if (isOpenSearch.value || searchText.value.length > 0)
    return searchResult.value
  else
    return dataList.value
})

const skeletonLength = ref(6)

watch(finalList, (newVal) => {
  if (newVal && newVal.length > 0)
    skeletonLength.value = newVal?.length
})

async function search() {
  const projectStatusCode = projectConfigStore.projectStatusCode[selectedTabName.value]
  const res = await fetchProjectListAPI({
    status: projectStatusCode,
    keyword: searchText.value.length > 0 ? searchText.value : undefined,
  }, userInfoStore.userInfo!.token!)
  return res.data!
}

onReady(() => {
  if (userInfoStore.belongTo(['0']))
    uni.setNavigationBarTitle({ title: '我的项目' })
  else if (userInfoStore.belongTo(['3', '4']))
    uni.setNavigationBarTitle({ title: '项目列表' })
  else if (userInfoStore.belongTo(['1', '2']))
    uni.setNavigationBarTitle({ title: '项目管理' })
})
onShow(async () => {
  await refreshAsync()
  setBadge()
})
/* -------------------------------- 列表数据 END -------------------------------- */

/* ------------------------------- 通用事件处理 START ------------------------------- */
const handleSearch = useDebounceFn((keyword: string) => {
  searchText.value = keyword
  fetchSearchResult()
}, 500)

async function handleTabChange(e: any) {
  selectedTabName.value = e.name
  uni.pageScrollTo({ scrollTop: 0, duration: 0 })
  await refreshAsync()
  setBadge()
}

async function setBadge() {
  const [status1Res, status2Res, status3Res] = await Promise.all([
    fetchProjectListAPI({ }, userInfoStore.userInfo!.token!),
    fetchProjectListAPI({ status: '2' }, userInfoStore.userInfo!.token!),
    fetchProjectListAPI({ status: '3' }, userInfoStore.userInfo!.token!),
  ])

  const total1 = status1Res.data?.data.length
  const total2 = status2Res.data?.data.length
  const total3 = status3Res.data?.data.length

  tabConfiguration.value = [
    { name: '全部', badge: { value: total1 } },
    { name: '施工中', badge: { value: total2 } },
    { name: '售后中', badge: { value: total3 } },
  ] as any
}

function handleTapProject(projectId: string) {
  router.push({
    name: 'projectDetail',
    params: {
      project_id: projectId,
    },
  })
}

function handleInitiateAfterSales(projectId?: string) {
  if (projectId) {
    router.push({
      name: 'initiateAfterSales',
      params: {
        project_id: projectId,
      },
    })
  }
  else { uni.showToast({ title: '发生错误', icon: 'none' }) }
}

function handleAssignTeammates(projectId: string) {
  router.push({
    name: 'teammates',
    params: {
      project_id: projectId,
    },
  })
}
/* -------------------------------- 通用事件处理 END -------------------------------- */

/* ------------------------------ 业务员事件处理 START ----------------------------- */
function handleUpdateUserInfo(project: Project) {
  if (project.id?.toString()) {
    router.push({
      name: 'updateUserInfoInProject',
      params: {
        project_id: project.id?.toString(),
        name: project.contacts_name || '',
        mobile: project.contacts_mobile || '',
      },
    })
  }
  else {
    uni.showToast({ title: '发生错误', icon: 'none' })
  }
}

function handleUploadPayment(projectId?: string) {
  if (projectId) {
    router.push({
      name: 'uploadPayment',
      params: {
        project_id: projectId,
      },
    })
  }
  else {
    uni.showToast({ title: '发生错误', icon: 'none' })
  }
}
/* ------------------------------- 业务员事件处理 END ------------------------------ */

/* ------------------------------ 工长事件处理 START ------------------------------ */
function handleUpdateProjectNode(projectId: string) {
  router.push({
    name: 'updateProjectNode',
    params: {
      project_id: projectId,
    },
  })
}
/* ------------------------------- 工长事件处理 END ------------------------------- */

/* ------------------------------ 财务事件处理 START ------------------------------ */
function handleViewPaymentRecord(projectId?: string) {
  if (projectId) {
    router.push({
      name: 'projectPaymentInfo',
      params: {
        project_id: projectId,
      },
    })
  }
  else {
    uni.showToast({ title: '发生错误', icon: 'none' })
  }
}
/* ------------------------------- 财务事件处理 END ------------------------------- */
</script>

<template>
  <!-- 页面 -->
  <view class="min-h-screen bg-#F8F8F8">
    <!-- 顶部搜索栏与 Tab 选项卡 -->
    <view v-if="userInfoStore.belongTo(['1', '2', '3', '4'])" class="z-10 sticky top-0 left-0 w-750rpx bg-white">
      <Spacer height="30" />
      <view class="mx-30rpx border-1px border-solid border-#E3E3E3 rounded-6rpx">
        <uv-search
          shape="square" bg-color="#F8F9FD" color="#000000" search-icon-size="36rpx"
          search-icon-color="#FF6D0A" placeholder-color="#999999" :show-action="false"
          height="74rpx" placeholder="请输入项目名称/房号搜索"
          @change="handleSearch" @focus="isOpenSearch = true" @blur="isOpenSearch = false"
        />
      </view>
      <Spacer height="10" />
      <uv-tabs
        :list="tabConfiguration" line-color="#FF6D0A" line-width="48rpx"
        :active-style="{ color: '#000000', fontSize: '32rpx', lineHeight: '32rpx' }"
        :inactive-style="{ color: '#999999', fontSize: '28rpx', lineHeight: '28rpx' }"
        :custom-style="{ margin: '0 10rpx' }"
        @change="handleTabChange"
      />
    </view>

    <!-- 骨架屏 -->
    <view v-if="loading || searching" class="p-30rpx bg-#F8F8F8">
      <!-- 骨架屏 Item -->
      <ProjectListCardUserSkeleton v-for="i in skeletonLength" v-show="userInfoStore.belongTo(['0'])" :key="i" />
      <ProjectListCardAdminSkeleton v-for="i in skeletonLength" v-show="userInfoStore.belongTo(['1', '2', '3', '4'])" :key="i" />
    </view>

    <block v-else>
      <!-- 真实列表数据 -->
      <uv-list v-if="finalList && finalList.length > 0" :custom-style="{ padding: '30rpx', backgroundColor: '#F8F8F8' }">
        <uv-list-item
          v-for="project in finalList" :key="project.id"
          :custom-style="{ borderRadius: '20rpx', marginBottom: '30rpx' }"
        >
          <!-- 卡片 -->
          <ProjectListCardUser v-if="userInfoStore.belongTo(['0'])" :project="project" @tap="handleTapProject(project.id!.toString())" />
          <ProjectListCardAdmin
            v-else
            :project="project"
            @tap="handleTapProject(project.id!.toString())"
            @update-user-info="handleUpdateUserInfo(project)"
            @upload-payment="handleUploadPayment(project.id?.toString())"
            @initial-after-sales="handleInitiateAfterSales(project.id?.toString())"
            @assign-teammates="handleAssignTeammates(project.id!.toString())"
            @update-project-node="handleUpdateProjectNode(project.id!.toString())"
            @view-payment-record="handleViewPaymentRecord(project.id?.toString())"
          />
        </uv-list-item>
      </uv-list>
      <!-- 页面缺省页 -->
      <PageDefault v-else />
    </block>
  </view>
</template>

<route lang="yaml">
name: 'projectList'
style:
  navigationBarBackgroundColor: '#FFFFFF'
  onReachBottomDistance: 100
layout: 'custom'
</route>
